/*******************************************************************************************
Copyright (C) 2013 Mestrelab Research S.L. All rights reserved.

This file is part of the MNova scripting toolkit.

Authorized users of MNova Software may use this file freely, but this file is provided AS IS
with NO WARRANTY OF ANY KIND, INCLUDING THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE.
*******************************************************************************************/

/*globals settings, Dir, FileDialog, File, TextStream, Application, NMRSpectrum, MnUi*/
/*jslint plusplus: true, indent: 4*/

function exportAll2DPeaks(aFileName) {
	"use strict";
	var fout, sout, doc, i, page, pageCount, j, itemCount, spec, l, peaks, freq1, freq2, k, n, peak,
		dirSetKey = "exportAll2DPeaks/Dir",
		saveDir = settings.value(dirSetKey, Dir.home());
	if (!aFileName) {
		aFileName = FileDialog.getSaveFileName("ASCII Files (*.txt)", "", saveDir);
		if (!aFileName) {
			return;
		}

		settings.setValue(dirSetKey, File.absDirPath(aFileName));
	}

	fout = new File(aFileName);
	try {
		if (fout.open(File.WriteOnly)) {
			sout = new TextStream(fout);
			doc = Application.mainWindow.activeDocument;
			for (i = 0, pageCount = doc.pageCount(); i < pageCount; i++) {
				page = doc.page(i);
				for (j = 0, itemCount = page.itemCount(); j < itemCount; j++) {
					spec = new NMRSpectrum(page.item(j));
					if (spec.isValid() && spec.dimCount === 2) { // if page item is a 2D spectrum
						for (l = 0; l < spec.specCount; l++) {
							spec.curSpecIndex = l;
							peaks = spec.peaks();
							peaks.sort(true, true);
							freq1 = 1.0;
							//freq1 = spec.frequency(1); // uncomment this line to get f1 coordinate in Hz instead of ppm
							freq2 = 1.0;
							//freq2 = spec.frequency(2); // uncomment this line to get f2 coordinate in Hz instead of ppm
							sout.writeln(spec.getParam("Data File Name"));
							for (k = 0, n = peaks.count; k < n; k++) {
								peak = peaks.at(k);
								sout.writeln(k + 1, "\t", peak.delta(2) * freq2, "\t", peak.delta(1) * freq1, "\t", peak.intensity, "\t", peak.annotation);
							}
							sout.writeln();
						}
					}
				}
			}
		}
	} finally {
		fout.close();
	}
}

if (this.MnUi && MnUi.scripts_nmr) {
	MnUi.scripts_nmr.scripts_nmr_ExportAll2DPeaks = exportAll2DPeaks;
}
